package com.ciwong.epaper.modules.scan.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.scan.bean.AnswerCard;
import com.ciwong.epaper.modules.scan.bean.HomeWorkCommitInfo;
import com.ciwong.epaper.modules.scan.util.ScanHandler;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.zxing.Result;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.zxing.decoding.DecodeHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 答题卡 Created by res-zwyan on 2015/8/7.
 */
public class AnswerCardActivity extends BaseActivity
{
    private String tag = "AnswerCardActivity";

    private static final int REQ_CODE_TO_JOIN_CLASS = 1;// 去加入班级requestCode

    /**
     * 正在识别
     */
    private static final int ANSWER_CARD_STATUS_RECOGNITION_ING = 0;

    /**
     * 继续扫描
     */
    private static final int ANSWER_CARD_STATUS_CONTINUE_SCAN = 1;

    /**
     * 重新扫描
     */
    private static final int ANSWER_CARD_STATUS_AGAIN_SCAN = 2;

    private GridView mGv;

    private List<AnswerCard> mAnswerCardList;

    private ArrayList<String> mPathList = new ArrayList<>();

    private String mRootPath;

    private ImageView mIvLeft, mIvRight, answerCardING;

    private TextView mTvWorkCount;

    private View mContainRight;

    private ScanHandler mScanHandler;

    private Button answerCardStatus, answerCardCommitWork;

    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565).build();

    private boolean mIsOutAnsewer = false;

    // private void doStateAgainScan()
    // {
    // state = STATE.AGAINSCAN;
    // runOnUiThread(new Runnable()
    // {
    // @Override
    // public void run()
    // {
    // answerCardStatus.setText("重新扫描");
    // answerCardCommitWork.setVisibility(View.INVISIBLE);
    // }
    // });
    // }
    //
    // private void doStateScaning()
    // {
    // runOnUiThread(new Runnable()
    // {
    // @Override
    // public void run()
    // {
    // answerCardING.setVisibility(View.VISIBLE);
    // Animation anim = AnimationUtils.loadAnimation(AnswerCardActivity.this,
    // R.anim.in_from_left);
    // answerCardING.startAnimation(anim);
    // answerCardStatus.setText("正在识别");
    // answerCardCommitWork.setVisibility(View.INVISIBLE);
    // }
    // });
    // }
    //
    // private static class STATE
    // {
    // CONTINUE_SCAN
    // }
    //
    // private void doStateContinueScan()
    // {
    // state = STATE.CONTINUE_SCAN;
    // runOnUiThread(new Runnable()
    // {
    // @Override
    // public void run()
    // {
    // answerCardStatus.setText("继续扫描");
    // answerCardCommitWork.setVisibility(View.VISIBLE);
    // }
    // });
    // }

    private ViewOnClickListener listener = new ViewOnClickListener()
    {
        @Override
        public void avertRepeatOnClick(View v)
        {
            int id = v.getId();
            if (id == R.id.iv_left)
            {
                BaseJumpManager.jumpToScanImage(AnswerCardActivity.this,
                        R.string.go_back, mPathList, 0);
            }
            else if (id == R.id.iv_right)
            {
                BaseJumpManager.jumpToScanImage(AnswerCardActivity.this,
                        R.string.go_back, mPathList, 1);
            }
            else if (id == R.id.answer_card_status)
            {
                continueScan();
            }
            else if (id == R.id.answer_card_commit_work)
            {
                commitWork();
            }
        }
    };

    private void doDeleteFile()
    {
        FileUtils.delete(new File(mRootPath).getParent());
    }

    @Override
    protected void preCreate()
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置无标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected int setView()
    {
        return R.layout.activity_answer_card;
    }

    @Override
    protected void findViews()
    {
        // mGv = (GridView) findViewById(R.id.gridView);
        mIvLeft = (ImageView) findViewById(R.id.iv_left);
        mIvRight = (ImageView) findViewById(R.id.iv_right);
        answerCardING = (ImageView) findViewById(R.id.answer_card_ing);
        mTvWorkCount = (TextView) findViewById(R.id.tv_work_count_num);
        answerCardStatus = (Button) findViewById(R.id.answer_card_status);
        answerCardCommitWork = (Button) findViewById(
                R.id.answer_card_commit_work);
    }

    @Override
    protected void initEvent()
    {
        mIvLeft.setOnClickListener(listener);
        mIvRight.setOnClickListener(listener);
        answerCardStatus.setOnClickListener(listener);
        answerCardCommitWork.setOnClickListener(listener);
    }

    @Override
    protected void init()
    {
        hideTitleBar();
        mScanHandler = ScanHandler.me();
        // mScanHandler.preparedoNewHomeWork();
        Intent intent = getIntent();
        mIsOutAnsewer = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_ACTION,
                false);
        mRootPath = intent.getStringExtra(IntentFlag.INTENT_FLAG_PATH)
                + File.separator;
        CWLog.e(tag, "root path = " + mRootPath);
        mAnswerCardList = (List<AnswerCard>) intent
                .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
    }

    @Override
    protected void loadData()
    {
        // mGv.setAdapter(new AnswerAdapter());
        // doStateScaning();
        answerCardStatus.setEnabled(false);
        answerCardCommitWork.setEnabled(false);
        if (mIsOutAnsewer)
        {
            answerCardStatus.setVisibility(View.GONE);
        }
        if (mAnswerCardList != null)
        {
            int len = mAnswerCardList.size();
            if (len > 0)
            {
                AnswerCard leftCard = mAnswerCardList.get(0);
                AnswerCard rightCard = mAnswerCardList.get(1);
                String pathLeft, pathRight;
                pathLeft = "file://" + mRootPath + leftCard.getAnswerCardName();
                pathRight = "file://" + mRootPath
                        + rightCard.getAnswerCardName();
                mPathList.add(pathLeft);
                mPathList.add(pathRight);
                // ImageLoader.getInstance().displayImage(pathLeft,
                // new ImageViewAware(mIvLeft), options);
                // ImageLoader.getInstance().displayImage(pathRight,
                // new ImageViewAware(mIvRight), options);
                loadAnswerCard(mIvLeft, pathLeft);
                loadAnswerCard(mIvRight, pathRight);

                checkAnswerCard(pathLeft, pathRight);
            }
        }
    }

    private void loadAnswerCard(final ImageView iv, String url)
    {
        ImageLoader.getInstance().loadImage(url, new ImageSize(800, 800),
                options, new ImageLoadingListener()
                {
                    @Override
                    public void onLoadingStarted(String s, View view)
                    {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view,
                            FailReason failReason)
                    {

                    }

                    @Override
                    public void onLoadingComplete(String s, View view,
                            Bitmap bitmap)
                    {
                        iv.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view)
                    {

                    }
                });
    }

    /**
     * 检测答题卡点
     * 
     * @param pathLeft
     *            左边图片路径
     * @param pathRight
     *            右边图片路径
     */
    public void checkAnswerCard(final String pathLeft, final String pathRight)
    {
        executeOtherThread(new Runnable()
        {
            @Override
            public void run()
            {
                Result resultLeft;
                Result resultRight;
                resultLeft = DecodeHandler.scanningImage(pathLeft);
                resultRight = DecodeHandler.scanningImage(pathRight);

                CWLog.e(tag, String.valueOf(resultLeft) + " "
                        + String.valueOf(resultRight));
                if (resultLeft != null && resultRight != null)
                {
                    onQualified();
                }
                else
                {
                    onDisqualification();
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 合格
     */
    private void onQualified()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                answerCardStatus.setEnabled(true);
                answerCardCommitWork.setEnabled(true);
            }
        });

    }

    /**
     * 不合格
     */
    private void onDisqualification()
    {

        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                final CWDialog cwDialog = new CWDialog(AnswerCardActivity.this);

                cwDialog.setMessage("未能成功识别答题卡");

                cwDialog.setCancelable(false);

                cwDialog.setPositiveButton("重新扫描",
                        new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        goBack(null);
                        cwDialog.dismiss();
                    }
                }, true, getResources()
                        .getDrawable(R.drawable.dialog_floor_selector));
                cwDialog.show();
            }
        });

    }

    /**
     * 继续扫描
     * 
     */
    public void continueScan()
    {
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        if (clazz == null)
        {
            // 如果未加入班级
            CWToast.makeText(this, "提交作业失败，未加入班级", CWToast.LENGTH_LONG, true)
                    .setToastType(CWToast.TOAST_TYPE_ERROR).show();
        }
        else
        {
            // EventBus.getDefault().post(new CommitHomeWorkEvent(false));
            commitHomeWork(false, false);
            mScanHandler.addWorkCount();
            finish(false);
        }
    }

    /**
     * 交作业
     * 
     */
    public void commitWork()
    {
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        if (clazz == null)
        {
            // 如果未加入班级
            showConfirmAddClassDialog();
        }
        else
        {
            // EventBus.getDefault().post(new CommitHomeWorkEvent(true));
            commitHomeWork(true, true);
            mScanHandler.addWorkCount();
            // goBack(v, true);
        }
    }

    /**
     * 未加入班级提示框
     */
    private void showConfirmAddClassDialog()
    {
        CWDialog dialog = new CWDialog(this, false, false);
        dialog.setMessage(R.string.no_add_class_tip);
        dialog.setCancelable(true);
        dialog.setPositiveButton(getString(R.string.add_class),
                new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        MeJumpManager.jumpToJoinClassActivity(R.string.go_back,
                                AnswerCardActivity.this,
                                IntentValue.JumpToJoinClassType.FROM_CLASS_LIST,
                                REQ_CODE_TO_JOIN_CLASS);
                    }
                }, true,
                getResources().getDrawable(R.drawable.dialog_floor_selector))
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data)
    {
        if (resultCode == RESULT_OK)
        {
            if (requestCode == REQ_CODE_TO_JOIN_CLASS)
            {// 加入班级成功
                commitHomeWork(false, true);
            }
        }
    }

    public void finish(boolean isFinish)
    {
        Intent in = new Intent();
        in.putExtra(IntentFlag.INTENT_FLAG_ACTION, isFinish);
        setResult(RESULT_OK, in);
        finish();
    }

    public void goBack(View v)
    {
        doDeleteFile();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        if (mContainRight == null)
        {
            mContainRight = findViewById(R.id.contain_right);
        }
        int workCount = mScanHandler.getWorkCount();
        if (workCount == 0)
        {
            mContainRight.setVisibility(View.GONE);
            mTvWorkCount.setVisibility(View.GONE);
        }
        else if (workCount > 0)
        {
            mContainRight.setVisibility(View.VISIBLE);
            mTvWorkCount.setVisibility(View.VISIBLE);
            mTvWorkCount.setText("(" + workCount + ")");
        }
    }

    private void commitHomeWork(final boolean isShowDialog,
            final boolean isJumpToWorkList)
    {
        try
        {
            if (!mScanHandler.hasAnswerCard())
            {
                CWToast.makeText(this, "还没有扫码", Toast.LENGTH_LONG, true)
                        .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                return;
            }
            long uid = ((BaseApplication) getApplication()).getUserInfoBase()
                    .getUserId();

            Intent intent = this.getIntent();
            Answer answer = new Answer();
            ScanHandler.HomeWorkData homeWorkData = mScanHandler
                    .getHomeWorkData();
            answer.setCodeId(homeWorkData.getCodeId());
            answer.setClassId(homeWorkData.getClazz().getClassId() + "");
            answer.setOldDoWorkId(homeWorkData.getDoworkId());
            DownLoadInfo mDownLoadInfo = (DownLoadInfo) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            Module mModule = (Module) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            int position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION,
                    0);
            if (mModule == null)
            {
                mModule = new Module();
                ModuleInfo moduleInfo = new ModuleInfo();
                moduleInfo.setModuleId(ModuleInfo.ModuleInfoId.MODULE_ID_TEST);
                List<ModuleContent> moduleContentList = new ArrayList<ModuleContent>();
                ModuleContent moduleContent = new ModuleContent();
                moduleContent.setResourceType(
                        ModuleContent.ResourceType.RESOURCE_TYPE_TEST);
                String textPapername = homeWorkData.getTextPaperName();
                if (TextUtils.isEmpty(textPapername))
                {
                    textPapername = getString(R.string.unit_test_txt);
                }
                moduleContent.setResourceName(textPapername);
                moduleContentList.add(moduleContent);
                mModule.setModuleInfo(moduleInfo);
                mModule.setResourceList(moduleContentList);
            }
            HomeWorkCommitInfo homeWorkCommitInfo = new HomeWorkCommitInfo();
            homeWorkCommitInfo.setAnswer(answer);
            homeWorkCommitInfo.setmDownLoadInfo(mDownLoadInfo);
            homeWorkCommitInfo.setmModule(mModule);
            homeWorkCommitInfo.setPosition(position);
            homeWorkCommitInfo.setUserId(uid);
            mScanHandler.commitHomework(homeWorkCommitInfo, new BaseExtCallBack(AnswerCardActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
            {


                @Override
                public void success()
                {
                    if (isShowDialog)
                    {
                        showSubmitingDialog();
                    }
                    else if (isJumpToWorkList)
                    {
                        finish(true);
                        MeJumpManager.jumpToStudyRecord(0,
                                AnswerCardActivity.this, R.string.go_back, 0);
                    }
                }

                @Override
                public void failed(int errorCode, Object data)
                {
                    super.failed(errorCode, data);
                    if(errorCode!=10004&&errorCode!=27&&errorCode!=17){
                        showToastError(errorCode,data);
                    }
                }

                @Override
                public void failed(Object data)
                {
                    super.failed(data);
                    CWToast.makeText(AnswerCardActivity.this,
                            R.string.submit_work_fail, CWToast.LENGTH_LONG,
                            true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 展示提交框
     */
    private void showSubmitingDialog()
    {
        CWDialog dialog = new CWDialog(this);
        // stopCamera();
        // stopCheckTip();
        dialog.setMessage(R.string.submit_work_success);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface dialog)
            {
                finish(true);
            }
        });
        dialog.setPositiveButton(R.string.look_detail,
                new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        finish(true);
                        if (!mIsOutAnsewer)
                        {
                            MeJumpManager.jumpToStudyRecord(0,
                                    AnswerCardActivity.this, R.string.go_back,
                                    1);
                            dialog.dismiss();
                        }
                    }
                }).setNegativeButton(R.string.i_know,
                        new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which)
                            {
                                finish(true);
                                dialog.dismiss();
                            }
                        })
                .show();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        mScanHandler.preparedoNewHomeWork();
    }
}